var express = require('express');
var router = express.Router();
var AV=require('leancloud-storage');
var busboy=require('connect-busboy');


router.get('/', function(req, res, next) {
	res.render('admin/index', {});

});

router.get('/blogList',function(req,res,next){
	res.render('admin/blogList',{list:[]});
})

router.get('/couponList',function(req,res,next){
	var query=new AV.Query('Coupons');
	query.find().then(function(results){
		console.dir(results);
		
		res.render('admin/couponList',{list:results});
	},function(error){

	})
})

router.get('/couponEdit',function(req,res,next){
	var id= req.query.id;
	console.log(id);
	var query=new AV.Query('Coupons');
	query.get(id).then(function(object){
		res.render('admin/couponEdit',{coupon:object});
	},function(error){
		console.error(error);
	})
	
})

router.get('/couponAdd',function(req,res,next){
	res.render('admin/couponAdd',{});
})

router.post('/couponAdd',function(req,res,next){
	var title=req.body.title;
	var imgId=req.body.imgId;
	var desc=req.body.desc;
	var saleUrl=req.body.saleUrl;

	var Coupons=AV.Object.extend('Coupons');
	var coupon=new Coupons();
	 coupon.set('title',title);
	 coupon.set('description',desc);
	 coupon.set('saleUrl',saleUrl);

	 var imgObj=AV.Object.createWithoutData('_File',imgId);
	 coupon.set('picture',imgObj);

	 coupon.save().then(function(object){
		res.send({result:1});
	 },function(error){
		 console.error(error);
		res.send({result:0});
	 })
})

router.post('/img',function(req,res,next){
	if (req.busboy) {
    	var base64data = [];
    	var pubFileName = '';
    	var pubMimeType = '';
    	req.busboy.on('file', (fieldname, file, fileName, encoding, mimeType) => {
      		var buffer = '';
      		pubFileName = fileName;
      		pubMimeType = mimeType;
      		file.setEncoding('base64');
      		file.on('data', function(data) {
        		buffer += data;
      		}).on('end', function() {
        		base64data.push(buffer);
      		});
    	}).on('finish', function() {
      		var f = new AV.File(pubFileName, {
        	// 仅上传第一个文件（多个文件循环创建）
        	base64: base64data[0]
      	});
      	try {
        	f.save().then(function(fileObj) {
          	// 向客户端返回数据
          	res.send({
            	fileId: fileObj.id,
            	fileName: fileObj.name(),
            	mimeType: fileObj.metaData().mime_type,
            	fileUrl: fileObj.url()
          		});
        	});
      	} catch (error) {
        	console.log('uploadFile - ' + error);
        	res.status(502);
      	}
    })
    req.pipe(req.busboy);
  	} else {
    	console.log('uploadFile - busboy undefined.');
    	res.status(502);
  	}
})


router.get('/userList',function(req,res,next){
	var query = new AV.Query('_User');
	query.find().then(function(results){
		console.dir(results);
		res.render('admin/userList',{list:results});
	},function(error){

	})
	
})

router.get('/userAdd',function(req,res,next){
	res.render('admin/userAdd',{});
})

router.post('/userAdd',function(req,res,next){
	AV.Cloud.useMasterKey();
	var userName=req.body.userName;
	var password=req.body.password;
	var email=req.body.email;

	var user=new AV.User();
  // 设置用户名
  user.setUsername(userName);
  // 设置密码
  user.setPassword(password);
  // 设置邮箱
  user.setEmail(email);
  user.signUp().then(function (loginedUser) {
    console.log(loginedUser);
  }, function (error) {
	  console.error(error);
  });
})

router.get('/login',function(req,res,next){
	res.render('admin/login',{});
})

router.post('/login',function(req,res,next){
	var userName=req.body.userName;
	var password=req.body.password;
	
	
})
module.exports = router;